package com.aisino.wxkp.action;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.aisino.wxkp.common.basic.WxkpBaseAction;


public class OtherFilterAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger log = Logger.getLogger(OtherFilterAction.class);
	final private java.util.Map<String,Object> paramConfig = new java.util.HashMap<String,Object>();

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String t =request.getRequestURI();
		if (t.indexOf(".action")>=0) {
			doFilter(request,response);
		}
	}

	public void doFilter(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
		try {
			String path=httpRequest.getRequestURI();
//			String content=httpRequest.getContextPath();
			log.info(path);
			   int index=path.lastIndexOf("/");
			   String doUrl=path.substring(index+1);
			   String [] array = doUrl.split("!");
			   String sAction=array[0];
			   WxkpBaseAction action=null;
			   String methodName=array[1].split("\\.")[0];
			   try
			   {
			     Class<?> c=Class.forName("com.aisino.wxkp.action."+sAction);
			     action=(WxkpBaseAction)c.newInstance();
//			     action.init();
			     action.init(getServletConfig());
			     action.service(httpRequest, httpResponse);
			     Method m=c.getMethod(methodName,new Class[]{HttpServletRequest.class,HttpServletResponse.class});
			     m.invoke(action, new Object[]{httpRequest,httpResponse});
			   }catch(ClassNotFoundException ex1){
				   httpResponse.sendRedirect("404.jsp");
			   }catch(Exception ex2){
				   httpResponse.sendRedirect("error.jsp");
				   ex2.printStackTrace();
			   }finally{
				   if(action!=null){
					   try {
							action.destroy();
						} catch (Throwable e) {}
				   }
			   }
		
		} catch (Exception ex) {
			ex.printStackTrace();
			httpResponse.sendRedirect("error.jsp");
		}
	}

	public void init() throws ServletException {
		System.out.println("FilterAction.init");
	}
	
	@SuppressWarnings("unchecked")
	public void init(ServletConfig config) throws ServletException {
		String ser = config.getServletName();
		System.out.println("ServletName="+ser);
		java.util.Enumeration<String> pams = config.getInitParameterNames();
		while (pams.hasMoreElements()){
			String k = pams.nextElement();
			String v = config.getInitParameter(k);
			paramConfig.put(k, v);
		}
		
	}
}
